package com.right.health.app.app;

import android.content.Context;
import android.support.multidex.MultiDex;
import android.util.Log;

import com.bumptech.glide.request.target.ViewTarget;
import com.hyphenate.easeui.EaseUI;
import com.hyphenate.push.EMPushHelper;
import com.hyphenate.push.EMPushType;
import com.hyphenate.push.PushListener;
import com.magic.basic.app.BaseApplication;
import com.magic.basic.utils.AppUtil;
import com.right.health.app.R;
import com.right.health.app.bean.AppUserResponse;
import com.right.health.app.bean.ChooseMemberInfo;
import com.right.health.app.constants.AppConfig;
import com.right.health.app.db.DaoSharedPreferences;
import com.right.health.app.greendao.DaoManager;
import com.right.health.app.hyphenate.DemoHelper;
import com.right.health.app.hyphenate.HMSPushHelper;
import com.right.health.app.push.TagAliasOperatorHelper;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import cn.jpush.android.api.JPushInterface;
import essclib.pingan.ai.request.biap.common.ApiConstants;
import hc.mhis.paic.com.essclibrary.EsscSDK;

import static com.right.health.app.push.TagAliasOperatorHelper.ACTION_GET;
import static com.right.health.app.push.TagAliasOperatorHelper.sequence;


/**
 * Application 入口
 * Created by Hope on 17/3/1.
 */

public class App extends BaseApplication {

    private static App mInstance;

    private AppUserResponse.AppUserInfo mUser;

    private ChooseMemberInfo mCurrMemberInfo;

    @Override
    protected void init() {
        MultiDex.install(this);
        mInstance = this;

        //这里是为了解决Glide报错问题,但是后续需要跟进原因
        ViewTarget.setTagId(R.id.glide_tag);

        //init demo helper
        DemoHelper.getInstance().init(this);

        // 请确保环信SDK相关方法运行在主进程，子进程不会初始化环信SDK（该逻辑在EaseUI.java中）
        if (EaseUI.getInstance().isMainProcess(this)) {
            // 初始化华为 HMS 推送服务, 需要在SDK初始化后执行
            HMSPushHelper.getInstance().initHMSAgent(mInstance);

            EMPushHelper.getInstance().setPushListener(new PushListener() {
                @Override
                public void onError(EMPushType pushType, long errorCode) {
                    // TODO: 返回的errorCode仅9xx为环信内部错误，可从EMError中查询，其他错误请根据pushType去相应第三方推送网站查询。
                    Log.e("PushClient", "Push client occur a error: " + pushType + " - " + errorCode);
                }
            });
        }

        EsscSDK.init(this, ApiConstants.URL_PRODUCT);
        closeAndroidPDialog();
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
        DaoManager.getInstance().init(this);
        TagAliasOperatorHelper.TagAliasBean setBean = new TagAliasOperatorHelper.TagAliasBean();
        setBean.action = ACTION_GET;
        setBean.isAliasAction = true;
        sequence++;
        TagAliasOperatorHelper.getInstance().handleAction(this, sequence, setBean);

    }

    /**
     * 去除安卓P私有API弹窗
     */
    private void closeAndroidPDialog() {
        try {
            Class aClass = Class.forName("android.content.pm.PackageParser$Package");
            Constructor declaredConstructor = aClass.getDeclaredConstructor(String.class);
            declaredConstructor.setAccessible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            Class cls = Class.forName("android.app.ActivityThread");
            Method declaredMethod = cls.getDeclaredMethod("currentActivityThread");
            declaredMethod.setAccessible(true);
            Object activityThread = declaredMethod.invoke(null);
            Field mHiddenApiWarningShown = cls.getDeclaredField("mHiddenApiWarningShown");
            mHiddenApiWarningShown.setAccessible(true);
            mHiddenApiWarningShown.setBoolean(activityThread, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean isDebugModel() {
        return AppConfig.IS_DEBUG;
    }

    public static boolean inMainProcess(Context context) {
        String packageName = context.getPackageName();
        String processName = AppUtil.getCurProcessName(context);
        return packageName.equals(processName);
    }

    public boolean isLogined() { //是否绑定手机号码
        return getUser() != null;
    }

    public void refreshUser(AppUserResponse.AppUserInfo info) {
        DaoSharedPreferences.getInstance().setUser(info);
        mUser = info;
    }

    public ChooseMemberInfo getCurrentMember() {
        if (mCurrMemberInfo == null) {
            mCurrMemberInfo = DaoSharedPreferences.getInstance().getChooseMember();
            if (mCurrMemberInfo == null && getUser() != null) {
                mCurrMemberInfo = new ChooseMemberInfo("本人", getUser().memberid, getUser().sex);
                DaoSharedPreferences.getInstance().setChooseMember(mCurrMemberInfo);
            }
        }
        return mCurrMemberInfo;
    }

    public void refreshChooseMember(ChooseMemberInfo info) {
        DaoSharedPreferences.getInstance().setChooseMember(info);
        mCurrMemberInfo = info;
    }

    /**
     * 获取账号信息
     *
     * @return 账号信息
     */
    public AppUserResponse.AppUserInfo getUser() {
        if (mUser == null) {
            mUser = DaoSharedPreferences.getInstance().getUser();
        }
        return mUser;
    }

    public String getUserId() {
        AppUserResponse.AppUserInfo userInfo = getUser();
        if (userInfo != null) {
            return userInfo.personid;
        }
        return "";
    }

    @Override
    protected void onDestory() {

    }

    /**
     * 获取app实例
     *
     * @return app实例
     */
    public static App getInstance() {
        return mInstance;
    }

    @Override
    public boolean isTranslucentStatus() {
        return true;
    }


    @Override
    public int getStatusBarColor() {
        return getResources()
                .getColor(R.color.color_09C3BE);
    }

    @Override
    public int getRefreshColor() {
        return R.color.color_09C3BE;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
}
